package com.harmonk.firstscene.ui.model

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.harmonk.firstscene.FirstSceneApplication
import com.harmonk.firstscene.db.entity.EventWithAll
import com.harmonk.firstscene.db.entity.TrafficEvent
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext

class TrafficEventViewModel(application: Application) : AndroidViewModel(application) {
    private val trafficEventRepository =
        (application as FirstSceneApplication).trafficEventRepository

    private val _trafficEvents = MutableLiveData<List<TrafficEvent>>()
    val trafficEvents: LiveData<List<TrafficEvent>> = _trafficEvents

    private val _currentEvent = MutableLiveData<TrafficEvent>()
    val currentEvent: LiveData<TrafficEvent> = _currentEvent

    init {
        loadTrafficEvents()
    }

    fun loadTrafficEvents() {
        viewModelScope.launch {
            try {
                trafficEventRepository.getAllTrafficEvents()
                    .collect { trafficEventList: List<TrafficEvent> ->
                        _trafficEvents.postValue(trafficEventList)
                    }
            } catch (e: Exception) {
                // Handle exception
                _trafficEvents.postValue(emptyList())
            }
        }
    }

    fun getCurrentEvent(id: Long) {
        viewModelScope.launch {
            try {
                trafficEventRepository.getEventById(id).collect { event ->
                    _currentEvent.postValue(event)
                }
            } catch (e: Exception) {
                // Handle exception
                // 输出获取失败的日志
                android.util.Log.e("TrafficEventViewModel", "Failed to get traffic event", e)
            }
        }
    }


    suspend fun insertTrafficEvent(trafficEvent: TrafficEvent): Long {
        val id = withContext(Dispatchers.IO) {
            trafficEventRepository.insertTrafficEvent(trafficEvent)
        }
        return id
    }

    fun updateTrafficEvent(trafficEvent: TrafficEvent) {
        viewModelScope.launch {
            try {
                trafficEventRepository.updateTrafficEvent(trafficEvent)
            } catch (e: Exception) {
                // Handle exception
            }
        }
    }

    fun deleteTrafficEvent(trafficEvent: TrafficEvent) {
        viewModelScope.launch {
            try {
                trafficEventRepository.deleteTrafficEvent(trafficEvent)
            } catch (e: Exception) {
                // Handle exception
            }
        }
    }
}

// 添加ViewModel工厂类
class TrafficEventViewModelFactory(private val application: Application) :
    ViewModelProvider.Factory {
    override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(TrafficEventViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return TrafficEventViewModel(application) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}